package com.xjoyt.pay.util;

/**
 * 就这美 2017
 */
import java.util.Date;

import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.beanutils.Converter;

/**
 * 
 * @版权：就这美 版权所有 (c) 2017
 * @ClassName:ExceptionUtil
 * @author liangzhm<br/>
 * @email liangzhm1985@foxmail.com
 * @version Revision 1.0.0
 * @since JDK 1.7
 * @创建日期：2017年5月5日下午3:58:38
 * @功能说明：
 * 
 */
public class ConvertUtil {

	@SuppressWarnings("unchecked")
	public static <T> T convert(Object obj, Class<T> targetType) {
		if (obj == null) {
			return null;
		}

		if (obj instanceof Date && targetType.equals(String.class)) {
			return (T) DateUtil.formatDate((Date) obj, DateUtil.DEFAULT_PATTERN);
		}

		if (obj instanceof String && targetType.equals(Date.class)) {
			return (T) DateUtil.parseDate((String) obj, DateUtil.DEFAULT_PATTERN);
		}

		Converter converter = ConvertUtils.lookup(targetType);
		if (converter == null) {
			throw new RuntimeException("can't cast [" + obj.getClass().getName() + "] to [" + targetType.getName() + "]");
		}

		try {
			return (T) converter.convert(targetType, obj);
		} catch (Exception e) {
			throw new RuntimeException("can't cast [" + obj.getClass().getName() + "] to [" + targetType.getName() + "]", e);
		}
	}
}
